import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * ReentrantLockCondition 的 await和signal的使用
 * 以及 while(条件不成立)时持续 await
 */
@Slf4j
public class TestReentrantLockMultiCondition {

    static final ReentrantLock LOCK = new ReentrantLock();
    static Condition waitHasCigarette = LOCK.newCondition();
    static Condition waitHasTakeout = LOCK.newCondition();

    static boolean hasCigarette = false;
    static boolean hasTakeout = false;

    public static void main(String[] args) {
        new Thread(() -> {
            LOCK.lock();
            try {
                log.info("有烟没?[{}]", hasCigarette);
                while (!hasCigarette) {
                    log.info("没烟，先歇会！");
                    waitHasCigarette.await();
                }
                log.info("有烟没?[{}]", hasCigarette);
                if (hasCigarette) {
                    log.info("可以开始干活了");
                } else {
                    log.info("没干成活！");
                }

            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                LOCK.unlock();
            }
        }, "小南").start();

        new Thread(() -> {
            LOCK.lock();
            try {
                log.info("外卖有没?[{}]", hasTakeout);
                while (!hasTakeout) {
                    log.info("没外卖，先歇会！");
                    waitHasTakeout.await();
                }
                log.info("外卖有没?[{}]", hasTakeout);
                if (hasTakeout) {
                    log.info("可以开始干活了");
                } else {
                    log.info("没干成活！");
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                LOCK.unlock();
            }
        }, "小女").start();

        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        new Thread(() -> {
            LOCK.lock();
            try {
                log.info("送外卖的 come in...");
                hasTakeout = true;
                waitHasTakeout.signal();
            } finally {
                LOCK.unlock();
            }
        }, "送外卖的").start();
    }

}
